package com.yunkai.plate_lpr;


import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import androidx.annotation.NonNull;

import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Toast;

import com.hyperai.hyperlpr3.HyperLPR3;
import com.hyperai.hyperlpr3.bean.HyperLPRParameter;
import com.yunkai.plate_lpr.R;

//import com.kernal.demo.plateid.R;

import java.lang.ref.WeakReference;
import java.util.Calendar;


public class CraREActivity extends Activity implements View.OnClickListener {

    private final int MY_PERMISSIONS_REQUEST_CAMERAAND_WRITE_EXTERNAL_STORAGE =3;
    private final int MY_PERMISSIONS_REQUEST_CAMERA =1;
    private final int MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE =2;
    private ImageView imageview =null;
    private Bitmap sucessbitmap = null;
    private Button noplate = null;
    private AutoFitTextureView textureView;
    private ImageButton startbtn;
    private ImageButton light;
    private SimpleRecog simpleRecog ;
    private CameraUtil cameraUtil;
    private HandlerR handler ;
    private boolean finish = false;//标记是否取消识别
    private String type;// 判断显示无牌车及手动输入
    //private SensorController sensorController;

    static class HandlerR extends Handler {
         private WeakReference<CraREActivity> mWeakReference;
         HandlerR(CraREActivity craREActivity){
             this.mWeakReference = new WeakReference<>(craREActivity);
         }

          @Override
          public void handleMessage(Message msg) {
              super.handleMessage(msg);
              final CraREActivity craREActivity = mWeakReference.get();

                  if(msg.what == 1){
                    if(craREActivity.finish){
                      return;
                    }
                      String plate = msg.getData().getString("plate");
                      String path = msg.getData().getString("path");
                      String online = msg.getData().getString("online");
                      Intent intent = new Intent();
                      intent.putExtra("path", path);
                      intent.putExtra("plate", plate);
                      intent.putExtra("online", online);
                      craREActivity.setResult(RESULT_OK, intent);
                      craREActivity.finish();

                  }else if(msg.what == 3){
                      craREActivity.imageview.setImageBitmap(craREActivity.sucessbitmap);
                      craREActivity.sucessbitmap = null;
                  }


          }
      }


    @Override
    public void onTrimMemory(int level) {
        super.onTrimMemory(level);
        switch (level){
            case TRIM_MEMORY_COMPLETE:
                Toast.makeText(this,"内存不足，进程即将结束",Toast.LENGTH_SHORT).show();
                break;
            case TRIM_MEMORY_MODERATE:
                Toast.makeText(this,"内存不足，进程可能结束",Toast.LENGTH_SHORT).show();
                break;
            case TRIM_MEMORY_BACKGROUND:
                Toast.makeText(this,"进程尚且安全",Toast.LENGTH_SHORT).show();
                break;
            case TRIM_MEMORY_UI_HIDDEN:
                Toast.makeText(this,"进程切换至后台",Toast.LENGTH_SHORT).show();
                break;
        }
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

      handler = new HandlerR(this);
      setStatusBarVisible(false);
      Intent intent = getIntent();
      type = intent.getStringExtra("type");
      Log.i("初始化", intent.getExtras().toString());
      //指定保存图片目录
        ImageUtil.parent = this.getCacheDir() + "/DETECTION/";

        init();
    }

    private void setStatusBarVisible(boolean show) {
        if (show) {
            int uiFlags = View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
            uiFlags |= 0x00001000;
            getWindow().getDecorView().setSystemUiVisibility(uiFlags);
        } else {
            int uiFlags = View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_FULLSCREEN;
            uiFlags |= 0x00001000;
            getWindow().getDecorView().setSystemUiVisibility(uiFlags);
        }
    }


    public void onConfigured(){
        Calendar c = Calendar.getInstance();
        int hour = c.get(Calendar.HOUR_OF_DAY);
        if(hour >= 19 || hour < 7){
            opencloseLight();
        }
    }
    private boolean startprv = false;
    public void startPrv(){
        startprv = true;
      imageview.setVisibility(View.VISIBLE);
    }

    private void init(){
        Log.i("cameraInit","正在初始化页面");
        setContentView(R.layout.activity_cra);

        light = findViewById(R.id.light);
        textureView = findViewById(R.id.capture);

        imageview = findViewById(R.id.imageview);

        startbtn = findViewById(R.id.startbtn);

        noplate = findViewById(R.id.noplate);
        if(type == null || type.equals("1")){
            type = "1";
          noplate.setText("手动");
        }else if(type.equals("2")){
          noplate.setText("无牌车");
        }
        noplate.setOnClickListener(this);


        DisplayMetrics metric = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metric);
        int width = metric.widthPixels;     // 屏幕宽度（像素）
        ViewGroup.LayoutParams lp = imageview.getLayoutParams();
        lp.width = width;
        imageview.setLayoutParams(lp);

        startbtn.setOnClickListener(this);
        light.setOnClickListener(this);

        //sensorController = new SensorController(this);//开启陀螺仪检测
        cameraUtil = new CameraUtil(this,textureView,imageview);//创建初始化相机
        textureView.setSurfaceTextureListener(cameraUtil.getSurfaceListener()); // 为该组件设置监听器
        simpleRecog = new SimpleRecog(CraREActivity.this,cameraUtil,imageview);//开启识别业务线程
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.startbtn) {
            startbtn.setVisibility(View.INVISIBLE);
            simpleRecog.setDETENTY(true);
        } else if (id == R.id.light) {
            opencloseLight();
        } else if (id == R.id.noplate) {
            finish = true;
            simpleRecog.stop();
            Intent intent = new Intent();
            if (type.equals("1")) {
                intent.putExtra("path", "none");
                intent.putExtra("plate", "input");
            } else if (type.equals("2")) {
                Bitmap[] bitmapArr = cameraUtil.getBitmap();
                String xcpic = ImageUtil.saveImage(this, bitmapArr[0]);
                intent.putExtra("path", xcpic);
                intent.putExtra("plate", "none");
            }

            intent.putExtra("online", "false");
            setResult(RESULT_OK, intent);
            finish();
        }
    }



    private boolean lightstatus = false;
    private void opencloseLight(){
        lightstatus = !lightstatus;
        if(lightstatus){
            light.setImageResource(R.drawable.ic_flashon_20dp);
        }else{
            light.setImageResource(R.drawable.ic_flashoff_20dp);
        }
        cameraUtil.setTorch(lightstatus);
    }


//    public void  OpenDetenty(){
//        //Toast.makeText(this,"KAISHI",Toast.LENGTH_SHORT).show();
//        if(simpleRecog != null){
//            simpleRecog.setDETENTY(true);
//        }
//    }
//
//    public void  CloseDetenty(){
//        if(simpleRecog != null){
//            simpleRecog.setDETENTY(false);
//        }
//        Toast.makeText(this,"请对准车牌，不用晃动手机", Toast.LENGTH_SHORT).show();
//    }



private void startDetenty(){
    startbtn.setVisibility(View.INVISIBLE);
    imageview.setImageBitmap(null);

}

    public void setBitmap(Bitmap bitmap){
        this.sucessbitmap=bitmap;
    }

    public Handler getHandler(){
        return this.handler;
    }

    private boolean isCameraInitialized = false; // 标志位，用于判断相机是否已初始化

    @Override
    protected void onResume() {
        super.onResume();
        Log.i("activity", "onResume: 恢复相机和界面");
        if (!isCameraInitialized) {
            init(); // 重新初始化相机和界面
            isCameraInitialized = true;
        }
    }

    @Override
    protected void onPause() {
        Log.e("activity", "onPause: 释放相机和界面资源");
        // 释放相机和相关资源
        if (lightstatus) {
            opencloseLight(); // 先关闭闪光灯
        }
        if (simpleRecog != null) {
            simpleRecog.onDestroy();
            simpleRecog = null; // 明确置空
        }
        if (cameraUtil != null) {
            cameraUtil.onDestroy();
            cameraUtil = null; // 明确置空
        }
        if (textureView != null) {
            textureView.setSurfaceTextureListener(null);
            if (textureView.getSurfaceTexture() != null) {
                textureView.getSurfaceTexture().release();
            }
        }
        if (ImageViewRec.getInstant() != null) {
            ImageViewRec.getInstant().stopScan(); // 停止扫描
        }

        if (imageview != null) {
            imageview.setOnClickListener(null);
            imageview = null;
        }

        sucessbitmap = null;
        isCameraInitialized = false; // 重置标志位
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        try {
            if (handler != null) {
                handler.removeCallbacksAndMessages(null); // 清除 Handler 中的所有消息和回调
                handler = null;
            }
            // 确保 SimpleRecog 的线程已停止
            if (simpleRecog != null) {
                simpleRecog.stop(); // 停止识别线程
                simpleRecog.onDestroy();
                simpleRecog = null;
            }
            // 确保 CameraUtil 的资源已释放
            if (cameraUtil != null) {
                cameraUtil.onDestroy();
                cameraUtil = null;
            }
            Log.e("activity", "已销毁对象");
        } catch (Exception e) {
            Log.e("onDestroy", "异常");
        }
        super.onDestroy();
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case MY_PERMISSIONS_REQUEST_CAMERA:
                if (grantResults.length > 0  && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    //Toast.makeText(CraREActivity.this,"初始化",Toast.LENGTH_SHORT).show();
                    init();
                }else {
                    Toast.makeText(CraREActivity.this,"未获取到相机权限,无法离线识别",Toast.LENGTH_SHORT).show();
                    this.finish();
                }
            break;
            case MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE :
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    //Toast.makeText(CraREActivity.this,"初始化",Toast.LENGTH_SHORT).show();
                    init();
                }else {
                    Toast.makeText(CraREActivity.this,"未获取到存储权限,无法离线识别",Toast.LENGTH_SHORT).show();
                    this.finish();
                }
                break;
            case MY_PERMISSIONS_REQUEST_CAMERAAND_WRITE_EXTERNAL_STORAGE:
                if (grantResults.length > 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
                    //Toast.makeText(CraREActivity.this,"初始化",Toast.LENGTH_SHORT).show();
                    init();
                }else {
                    Toast.makeText(CraREActivity.this,"未获取到相机和存储权限,无法离线识别",Toast.LENGTH_SHORT).show();
                    this.finish();
                }
                break;
        }
    }


    @Override
    public void onBackPressed() {
      Intent intent = new Intent();
      if(type.equals("1")){
        intent.putExtra("plate", "inputback");
      }else if(type.equals("2")){
        intent.putExtra("plate", "noneback");
      }
      intent.putExtra("path", "none");
      intent.putExtra("online", "false");
      setResult(RESULT_OK, intent);
      finish();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(!startprv){
            return true;
        }
        return super.onKeyDown(keyCode, event);

    }
}



